package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.client.api.shoppingcart.query.IQueryShoppingCartService;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartItemFeeDTO;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.util.OrderFeeUtil;
import com.iwhalecloud.bss.kite.manager.util.ManagerUtils;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 费用处理
 */
@Component
public class AcctItemHandler extends AbstractOrderHandler {

    @Override
    public boolean canHandle(OrderRequest orderRequest) {
        if (Objects.equals(Boolean.TRUE, orderRequest.getPreCheck())) {
            // 订单预校验流程不生成费用
            return false;
        }

        return true;
    }

    @Override
    public void doHandle(OrderRequest orderRequest) {
        // 获取购物车费用信息
        Map<String, List<ShoppingCartItemFeeDTO>> shoppingCartItemFeeMap = getCartItemFeeMap(
            orderRequest.getSceneInstIds(), orderRequest.getCustId());
        orderRequest.getGroupInstContainer().setShoppingCartItemFeeMap(shoppingCartItemFeeMap);

        OrderFeeUtil.dealAcctItem(orderRequest);
    }

    /**
     * 获取购物车费用信息
     * @param sceneInstIds
     * @param custId
     * @return
     */
    private Map<String, List<ShoppingCartItemFeeDTO>> getCartItemFeeMap(List<String> sceneInstIds, String custId) {
        if (CollectionUtils.isEmpty(sceneInstIds) || StringUtils.isBlank(custId)) {
            return new HashMap<>();
        }

        IQueryShoppingCartService queryShoppingCartService = SpringUtil.getBean(IQueryShoppingCartService.class);
        List<ShoppingCartItemFeeDTO> cartItemFees = new ArrayList<>();
        for (String sceneInstId : sceneInstIds) {
            cartItemFees
                .addAll(queryShoppingCartService.listPosShoppingCartItemFees(sceneInstId, custId).getResultObject());
        }
        // 过滤无效费用,实收费用项为0,审批费用项为0,优惠费用为0则认为无效,不用处理
        Map<String, List<ShoppingCartItemFeeDTO>> cartItemFeeMap = cartItemFees.stream().filter(
            fee -> !KiteStringUtils.equalsAll("0.00", fee.getAmount(), fee.getPerferAmount(), fee.getAdjustAmount()))
            .collect(Collectors.groupingBy(fee -> ManagerUtils.join(fee.getCartItemCd(), fee.getObjId())));

        return cartItemFeeMap;
    }
}
